#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void without_mutex();
void with_mutex();
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main(){
	without_mutex();
	with_mutex();
}

void* without_mutex_function(void* ptr){
	int* data_p = (int*)ptr;
	for(int i = 0; i < 100000; i++){
		*data_p += 1;
	}
	return NULL;
}

void* with_mutex_function(void* ptr){
	int* data_p = (int*)ptr;
	for(int i = 0; i < 100000; i++){
		pthread_mutex_lock(&mutex);
		*data_p += 1;
		pthread_mutex_unlock(&mutex);
	}
	return NULL;
}

void function(char with_mutex){
	pthread_t thread1, thread2;
	int data = 0;
	if (with_mutex){
		pthread_create(&thread1, NULL, with_mutex_function, (void *) &data);
		pthread_create(&thread2, NULL, with_mutex_function, (void *) &data);
	}else{
		pthread_create(&thread1, NULL, without_mutex_function, (void*) &data);
		pthread_create(&thread2, NULL, without_mutex_function, (void*) &data);
	}
	pthread_join(thread1, NULL);
	pthread_join(thread2, NULL);
	printf("with_mutex: %d, and data: %d\n", with_mutex, data);
}

void without_mutex(){
	function(0);
}

void with_mutex(){
	function(1);
}
